//
// Unihan Input Method
//
// Copyright © 2002-2007 Sun Wah Linux Ltd.
//
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
// USA
//
// $Id: testcommit.c 757 2007-05-10 08:19:31Z roger $
//

#include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>

static Display *display = NULL;
static Window owner;

int 
main(int argc, char *argv[])
{
	char *string = NULL;
	
	if (argc < 2) {
		fprintf(stderr, "Usage: %s commit_string\n", argv[0]);
		exit(EXIT_FAILURE);
	}
	string = malloc(strlen(argv[1]) + 1);
	strcpy(string, argv[1]);

	display = XOpenDisplay(NULL);
	if (!display) {
		fprintf(stderr, "Could not open display\n");
		exit(EXIT_FAILURE);
	}

	owner = XCreateSimpleWindow(display, DefaultRootWindow(display), 0, 0, 1, 1, 0, 0, 0);
	XSetSelectionOwner(display, XInternAtom(display, "_UNIHAN_COMMIT_STRING", False), owner, CurrentTime);

	while (1) {
		XEvent xev;
		XSelectionRequestEvent *ev;
		XSelectionEvent snev;
		
		XNextEvent(display, &xev);
		if (xev.type != SelectionRequest)
			continue;
		ev = &(xev.xselectionrequest);
		
		if (strcmp("_UNIHAN_COMMIT_STRING", XGetAtomName(display, ev->selection)))
			continue;
		if (strcmp("UTF8_STRING", XGetAtomName(display, ev->target)))
			continue;

		printf("commit: %s, req %x own %x prop %s\n", string, 
				ev->requestor, ev->owner, 
				XGetAtomName(display, ev->property));
		XChangeProperty(display, ev->requestor, ev->property, 
				XInternAtom(display, "UTF8_STRING", False),
				8, PropModeReplace, string, strlen(string));
		
		snev.type = SelectionNotify;
		snev.serial = 0;
		snev.send_event = True;
		snev.display = display;
		snev.requestor = ev->requestor;
		snev.selection = ev->selection;
		snev.target = ev->target;
		snev.property = ev->property;
		snev.time = CurrentTime;
		XSendEvent(display, ev->requestor, False, 0, (XEvent *)&snev);
		XFlush(display);
		break;
	}

	XCloseDisplay(display);
	return 0;
}

// vi:ts=4:nowrap:cin:expandtab
